package com.atelier.plugin.projectWizard.ui;


import com.atelier.plugin.projectWizard.util.DefaultNamingUtil;
import com.intellij.ide.starters.shared.TextValidationFunction;
import com.intellij.ide.starters.shared.ValidationFunctions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.roots.ui.configuration.JdkComboBox;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBLabel;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class ProjectSetting
{
    private JTextField group;
    private JTextField artifact;
    private JTextField packageName;
    private JPanel mainJpanel;
    private JTextField version;
    private JTextField name;
    private JPanel jdkSetting;
    private TextFieldWithBrowseButton locationBrowseButton;
    private boolean updatingFields; // 标志位，用于跟踪更新来源
    private boolean validateResult;
    private String baseDirectory;
    public ProjectSetting(String defaultBaseDirectory)
    {
        baseDirectory=defaultBaseDirectory;
        version.setText("0.0.1-SNAPSHOT");
        String s = DefaultNamingUtil.generateUniqueName(defaultBaseDirectory);
        System.out.println(s);
        name.setText(s);
        artifact.setText(s);
        locationBrowseButton.setText(defaultBaseDirectory + "\\" + name.getText());
        // 为 locationBrowseButton 添加点击事件监听器
        locationBrowseButton.addActionListener(e ->
        {
            FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, false, false, false, false);
            descriptor.setTitle("Select Project Location");
            descriptor.setDescription("Choose the directory where the project will be created.");
            descriptor.setShowFileSystemRoots(true);
            VirtualFile[] files = FileChooser.chooseFiles(descriptor, null, null);
            if (files.length > 0)
            {
                String selectedPath = files[0].getPath();
                selectedPath = selectedPath.replace("/", "\\"); // 将反斜杠替换为正斜杠
                System.out.println(selectedPath);
                baseDirectory=selectedPath;
                locationBrowseButton.setText(selectedPath + "\\" + name.getText());
                File uniqueName = new File(selectedPath, name.getText());
                if (uniqueName.exists())
                {
                    name.setText(DefaultNamingUtil.generateUniqueName(selectedPath));
                    locationBrowseButton.setText(selectedPath + "\\" + name.getText());
                }
            }

        });
        DocumentListener documentListener = new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            @Override
            public void removeUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            @Override
            public void changedUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            private void updateFields(Document document)
            {
                if (updatingFields)
                {
                    return; // 如果正在更新其他文本框，则直接返回，避免无限循环
                }

                updatingFields = true; // 设置标志位，表示正在更新文本框

                String nameText = name.getText();
                String artifactText = artifact.getText();
                try
                {
                    document.remove(0, document.getLength());
                    document.insertString(0, nameText, null);
                } catch (Exception ex)
                {
                    System.err.println("java.lang.IllegalStateException: Attempt to mutate in notification");
                    //ex.printStackTrace();
                }

                if (document == name.getDocument())
                {
                    artifact.setText(nameText);
                    locationBrowseButton.setText(baseDirectory + "\\" + nameText);
                }
                else if (document == artifact.getDocument())
                {
                    name.setText(artifactText);
                }

                updatingFields = false; // 更新完成，重置标志位
            }
        };
        // 设置输入验证和错误提示
        setupInputValidation();
        name.getDocument().addDocumentListener(documentListener);

        //artifact.getDocument().addDocumentListener(documentListener);
    }

    // 新增：输入验证方法
    public Boolean validateFields()
    {
        boolean isGroupValid = validateAndSetTooltips(group,ValidationFunctions.CHECK_GROUP_FORMAT);
        boolean isArtifactValid = validateAndSetTooltips(artifact,ValidationFunctions.CHECK_ARTIFACT_SIMPLE_FORMAT, ValidationFunctions.CHECK_ARTIFACT_FORMAT_FOR_WEB);
        boolean isNameValid = validateAndSetTooltips(name, ValidationFunctions.CHECK_SIMPLE_NAME_FORMAT);
        boolean isLocationValid = validateAndSetTooltips(locationBrowseButton.getTextField(),ValidationFunctions.CHECK_LOCATION_FOR_ERROR);
        boolean isPackageNameValid = validateAndSetTooltips(packageName, ValidationFunctions.CHECK_PACKAGE_NAME);
        validateResult = isGroupValid && isArtifactValid && isNameValid && isLocationValid && isPackageNameValid;
        return validateResult;
    }

    private void setupInputValidation()
    {
        DocumentListener documentListener = new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            @Override
            public void removeUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            @Override
            public void changedUpdate(DocumentEvent e)
            {
                updateFields(e.getDocument());
            }

            private void updateFields(javax.swing.text.Document document)
            {
                // 更新字段的逻辑...
                validateFields();
            }
        };
        name.getDocument().addDocumentListener(documentListener);
        artifact.getDocument().addDocumentListener(documentListener);
        group.getDocument().addDocumentListener(documentListener);
        packageName.getDocument().addDocumentListener(documentListener);
        locationBrowseButton.getTextField().getDocument().addDocumentListener(documentListener);
    }
    public Boolean validateAndSetTooltips(JTextField jTextField,  TextValidationFunction... validationFunctions) {
        Boolean result = true;
        List<String> errorMessages = new ArrayList<String>();
         String text = jTextField.getText();
        if(text!=null )
        {
             String errorMsg = ValidationFunctions.CHECK_NOT_EMPTY.checkText(text);
             if(errorMsg != null&&!errorMsg.isEmpty()){
                 jTextField.setBorder(BorderFactory.createLineBorder(new Color(  	205 ,85 ,85),2));
                 jTextField.setToolTipText(errorMsg);
                 return false;
             }
            for (TextValidationFunction validationFunction : validationFunctions)
            {
                String errorMessage = validationFunction.checkText(text);
                if (errorMessage != null && !errorMessage.isEmpty())
                {
                    errorMessages.add(errorMessage);
                }
            }
        }
        if (!CollectionUtils.isEmpty(errorMessages)) {
            result=false;
            jTextField.setBorder(BorderFactory.createLineBorder(new Color(  	205 ,85 ,85),2));
            jTextField.setToolTipText(errorMessages.get(0));
        } else {
            jTextField.setToolTipText("");
            jTextField.setBorder(UIManager.getBorder("TextField.border")); // 恢复默认边框样式
        }
        return result;
    }

}
